package com.example.demo.web;

import com.example.demo.dao.User;
import com.example.demo.model.UserServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/**
 * Created by huxin on 2017/7/31.
 */
@RestController
@RequestMapping(value = "/users")
public class UserController {
//    static Map<Long, User> users= Collections.synchronizedMap(new HashMap<Long, User>());

    @Autowired
    UserServiceImpl userService;

    @ApiOperation(value = "获取用户列表", notes = "获得已存在的用户")
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> getUserList(){
        List<User> userList = userService.getAllUsers();
        return userList;
    }

    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", dataType = "User", required = true)
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String postUser(@ModelAttribute User user){
        userService.create(user.getName(), user.getAge());
        return "success";
    }

    @ApiOperation(value = "获得用户", notes = "指定id")
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "Long", required = true, paramType = "path")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id){
        return userService.getUserById(id);
    }

    @ApiOperation(value = "更新信息", notes = "更新指定id用户信息")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "id", value = "用户id", dataType = "Long", required = true, paramType = "path"),
                    @ApiImplicitParam(name = "user", value = "用户实体", dataType = "User", required = true)
            }
    )
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ModelAttribute User user){
        User u = userService.getUserById(id);
        u.setAge(user.getAge());
        u.setName(user.getName());
        userService.update(u);
        return "success";
    }

    @ApiIgnore
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id){
        userService.deleteById(id);
        return "success";
    }
}
